package com.zcyr.core.impl;

import com.zcyr.core.AbstractDatabaseEnvironment;
import com.zcyr.exception.DatabaseEnvironmentException;
import com.zcyr.exception.TrymeUserSQLException;
import com.zcyr.pojo.*;
import com.zcyr.util.DatabaseTool;
import com.zcyr.util.SQLTrim;
import com.zcyr.util.SpringContextTool;
import com.zcyr.util.StatementTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DatabaseEnvironment extends AbstractDatabaseEnvironment {

    DatabaseTool databaseTool;

    final Logger logger = LoggerFactory.getLogger(getClass());

    protected DatabaseEnvironment(String url, DatabaseEnvironmentInfo info) {
        super(url, info);
        databaseTool = SpringContextTool.getBean(DatabaseTool.class);
    }


    @Override
    public List<SQLResult> executeSQL(String sql) throws TrymeUserSQLException, DatabaseEnvironmentException {
        try{
            return super.executeSQL(sql);
        }catch (DatabaseEnvironmentException e){
            throw new DatabaseEnvironmentException("无法建立与环境的连接, 请稍后再试!", e);
        }
    }

    @Override
    public int releaseTables() throws DatabaseEnvironmentException {
        int count = 0;
        try(Statement stmt = this.getConnection().createStatement()) {
            ArrayList<DatabaseTableInfo> tables = databaseTool.getAllTable(this.getUsername());
            for(DatabaseTableInfo info : tables){
                stmt.executeUpdate(String.format("DROP TABLE %s", info.tablename));
                ++count;
            }
            return count;
        } catch (SQLException throwables) {
            throw new DatabaseEnvironmentException("无法释放数据库环境的tables, 环境: " + this + " SQLException: " + throwables.getMessage());
        }
    }


    @Override
    public int releaseSchemas() throws DatabaseEnvironmentException {
        int count = 0;
        try(Statement stmt = this.getConnection().createStatement()) {
            ArrayList<DatabaseSchemaInfo> schemas = databaseTool.getAllSchema(this.getUsername());
            schemas.removeIf(item -> item.schemaName.equals(this.getUsername()));
            for (DatabaseSchemaInfo schema : schemas) {
                stmt.executeUpdate(String.format(
                        "DROP SCHEMA %s CASCADE;",
                        schema.schemaName
                ));
                ++count;
            }
            return count;
        } catch (SQLException throwables) {
            throw new DatabaseEnvironmentException("无法释放数据库环境的schema, 环境: " + this + " SQLException: " + throwables.getMessage());
        }
    }

    @Override
    public int releaseUsers() throws DatabaseEnvironmentException {
        int count = 0;
        try(Statement stmt = getConnection().createStatement()) {
            ArrayList<PgUser> members =  databaseTool.getUsers("usename LIKE '%" + SQLTrim.generateSuffix(this.getUuid()) + "'");
            for (PgUser member : members) {
                String sql = String.format("DROP USER %s CASCADE", member.getUsename());
                stmt.executeUpdate(sql);
                ++count;
            }
            return count;
        } catch (SQLException throwables) {
            throw new DatabaseEnvironmentException("无法释放数据库环境的users, 环境: " + this + " SQLException: " + throwables.getMessage());
        }
    }
}
